package org.dream.ui.chart.impl;

import static org.dream.ui.chart.impl.KChart.DOUIMG_P_DAY;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.InputEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;

import org.dream.adam.DoubleImage;
import org.dream.domain.Daydeal;
import org.dream.domain.RisewidthResult;
import org.dream.persistence.PersistenceService;
import org.dream.persistence.PersistenceServiceImpl;
import org.dream.service.Calculate;
import org.dream.ui.KChartSetDialog;
import org.dream.ui.MainFrame;
import org.dream.ui.chart.Chart;
import org.dream.ui.chart.Polyline;
import org.dream.ui.chart.RectTip;
import org.dream.zt.RisewidthResultService;
import org.dream.zt.RisewidthResultServiceImpl;

/**
 * 
 * @author qiuriyuchen E-mail:panpan_001@126.com
 */
public class KChart extends Chart {

	// 上一个开始时间

	public KChart(String stockCode, String startdate, String enddate) {
		this.stockCode = stockCode;
		daydealNowList = persistenceService.findDaydealsByCode(stockCode, startdate, enddate);
		List<Daydeal> afterMonthList = DoubleImage.getDaydealsImage(daydealNowList, yuCeDay);
		daydealViewList.addAll(daydealNowList);
		daydealViewList.addAll(afterMonthList);

		buildChart();

	}

	public void rebuildStockKChart() {
		buildChart();

	}

	public void refreshImage(int now) {
		if (KChart.DOUIMG_P_FLAG) {
			new ImageKPlot(daydealViewList, this, 1, now, DOUIMG_P_DAY).setId("IMAGEKPLOT");
		} else {
			this.clearPlot("IMAGEKPLOT");
		}
		this.repaint();

	}

	private void buildChart() {

		/**
		 * 计算时间刻度，及股票价格高点和低点
		 */
		Map<Integer, String> tickViews = new HashMap<Integer, String>();// 从1开始

		for (int i = 0; i < daydealViewList.size(); i++) {
			Daydeal daydeal = daydealViewList.get(i);
			tickViews.put((i + 1), daydeal.getDAY());
		}
		XAxisImpl xAxis = (new XAxisImpl(1, daydealViewList.size(), tickViews));
		YAxisImpl yAxis = (new YAxisImpl(10, 0.6));
		xAxis.getXAxisModel().setDrawGrid(false);
		yAxis.getYAxisModel().setDrawGrid(true);
		this.setAxis(xAxis, yAxis);

		/** 价格K线 */
		new KPlot(daydealViewList, this, 1);
		addCmap();
		/** 第二区域 */
		YAxisImpl yAxis2 = (new YAxisImpl(10, 0.4));
		yAxis2.getYAxisModel().setDrawGrid(true);
		this.addYAxis(2, yAxis2);
		if (VOL_P_FLAG) {
			refreshVolp();
		}
		if (JS_MA_P_FLAG) {
			refreshJsmap();
		}
		this.setBackground(Color.BLACK);

		addListener();

	}

	/**
	 * 添加收盘均线
	 */
	private void addCmap() {
		List<Double> clist = new ArrayList<Double>();
		for (Daydeal daydeal : daydealNowList) {
			clist.add(daydeal.getCLOSE());
		}
		List<Double> cmalist = Calculate.ma(clist, 60);
		new Polyline(cmalist, this, 1).setUi(Color.GREEN, 0, true).setId(KChart.C_MA_P_ID);
	}

	public void refreshJsmap() {

		if (this.stockCode.equals("999999") && JS_MA_P_FLAG) {

			ztList = risewidthResultService.findRisewidthResults(JS_MA_P_TURNOVER);

			List<Double> ydate = new ArrayList<Double>();
			for (int i = 0; i < 2254; i++) {
				ydate.add(0d);
			}
			for (RisewidthResult ztStockNum : ztList) {
				// ydate.add(ztStockNum.getADVANCE() + 0.0d);
				ydate.add(ztStockNum.getADVANCEPercentage());
			}
			// new Polyline(ydate, this, 2);
			// 均线
			List<Double> ydateJun = Calculate.ma(ydate, 60);
			new Polyline(ydateJun, this, 2).setUi(Color.WHITE, 0, true).setId(KChart.JS_MA_P_ID);
		} else {
			this.clearPlot(JS_MA_P_ID);
		}
		this.repaint();
	}

	public void addJsmap0() {
		if (this.stockCode.equals("999999")) {

			ztList = risewidthResultService.findRisewidthResults(0);

			List<Double> ydate = new ArrayList<Double>();
			for (int i = 0; i < 2254; i++) {
				ydate.add(0d);
			}
			for (RisewidthResult ztStockNum : ztList) {
				// ydate.add(ztStockNum.getADVANCE() + 0.0d);
				ydate.add(ztStockNum.getADVANCEPercentage());
			}
			// new Polyline(ydate, this, 2);
			// 均线
			List<Double> ydateJun = Calculate.ma(ydate, 60);
			new Polyline(ydateJun, this, 2).setUi(Color.YELLOW, 0, true).setId(KChart.JS_MA_P0_ID);
		}
	}

	public void refreshVolp() {
		if (KChart.VOL_P_FLAG) {
			new VolPlot(daydealViewList, this, 2).setId(KChart.VOL_P_ID);
		} else {
			this.clearPlot(KChart.VOL_P_ID);
		}
		this.repaint();

	}

	@Override
	public void paint(Graphics g) {
		this.chartModel.setTitle("开始时间："
				+ this.getXAxis().getXAxisModel().getTickDay(xAxis.getXAxisModel().getMinValue()) + "，结束时间："
				+ this.getXAxis().getXAxisModel().getTickDay(xAxis.getXAxisModel().getMaxValue()));
		tips.clear();

		super.paint(g);
		/** 画分隔线 */
		g.setColor(Color.RED);
		int x = this.getXAxis().getXAxisModel().translateValueToPx(daydealNowList.size())
				+ (int) this.getXAxis().getXAxisModel().getTickSpacingPixel() / 2;

		g.drawLine(x, this.getChartModel().getPixelYTop(), x, this.getChartModel().getPixelYButtom());
		/** 画十字星线 */
		if (mouseDoubleClick) {
			g.setColor(Color.WHITE);
			g.drawLine(this.getChartModel().getPixelXLeft(), mouseDoubleClickY, this.getChartModel().getPixelXRight(),
					mouseDoubleClickY);
			g.drawLine(mouseDoubleClickX, this.getChartModel().getPixelYTop(), mouseDoubleClickX, this.getChartModel()
					.getPixelYButtom());
		}

	}

	// 设置区域提示
	public void addRectTip(RectTip rectTip) {
		// this.tips.add(rectTip);
	}

	/**
	 * 添加监听器
	 */
	private void addListener() {
		this.addMouseMotionListener(new KChartMouseListener());

		/** 添加鼠标点击监听器 */
		this.addMouseListener(new MouseAdapter() {
			@Override
			public void mousePressed(MouseEvent e) {
				int mods = e.getModifiers();
				// 鼠标右键
				if ((mods & InputEvent.BUTTON3_MASK) != 0) {
					final int x = e.getX();
					final int y = e.getY();

					new KChartSetDialog((JFrame) KChart.this.getTopLevelAncestor(), true, KChart.this, x, y);
				}
				super.mousePressed(e);
			}

			@Override
			public void mouseClicked(MouseEvent e) {
				super.mouseClicked(e);
				if (e.getClickCount() == 2) {
					mouseDoubleClick = (mouseDoubleClick ? false : true);
					mouseDoubleClickX = e.getX();
					mouseDoubleClickY = e.getY();
					KChart.this.repaint();
				}
			}

		});
	}

	public Integer getMouseX() {
		return mouseX;
	}

	class KChartMouseListener extends MouseMotionAdapter {
		JDialog tipDialog = new JDialog((JFrame) KChart.this.getTopLevelAncestor(), true);

		public void mouseMoved(MouseEvent e) {
			mouseX = e.getX();
			if (mouseDoubleClick) {
				mouseDoubleClickX = e.getX();
				mouseDoubleClickY = e.getY();
				if (mouseDoubleClick) {
					KChart.this.repaint();
				}
			}

			int i = (int) KChart.this.getXAxis().getXAxisModel().translatePxToValue(e.getX());
			MainFrame.getInstanse().setStateText(
					KChart.this.chartModel.getTitle() + "鼠标位置：" + i + "真实日期"
							+ (KChart.this.getXAxis()).getXAxisModel().getTickDay(i));
			// kmove(e);
			/** 鼠标移动，镜像移动 */
			if (DOUIMG_P_FLAG) {
				KChart.this.clearPlot("IMAGEKPLOT");
				KChart.this.refreshImage(i);
				KChart.this.repaint();

			}

		}

		private void kmove(MouseEvent e) {
			/** K线区域 */
			boolean exsit = false;

			for (RectTip rectTip : tips) {
				if (e.getX() > rectTip.getX1() && e.getX() < rectTip.getX2() && e.getY() > rectTip.getY1()
						&& e.getY() < rectTip.getY2()) {

					tipDialog.add(new JLabel(rectTip.getTipStr()));
					tipDialog.setSize(100, 200);
					tipDialog.setLocation(e.getX(), e.getY());
					tipDialog.setVisible(true);
					exsit = true;
				}
			}
			if (!exsit) {
				tipDialog.setVisible(false);
			}
		}
	}

	private PersistenceService persistenceService = new PersistenceServiceImpl();
	RisewidthResultService risewidthResultService = new RisewidthResultServiceImpl();
	// 股票图形

	// 股票列表
	private List<Daydeal> daydealNowList = new ArrayList<Daydeal>();
	private List<Daydeal> daydealViewList = new ArrayList<Daydeal>();

	// 上一个股票代码
	private String stockCode;
	private List<RectTip> tips = new ArrayList<RectTip>();
	private List<RisewidthResult> ztList;
	// 预测时间
	int yuCeDay = 20;
	private int kind = 1;
	private boolean mouseDoubleClick;
	private Integer mouseDoubleClickX;
	private Integer mouseDoubleClickY;

	public static boolean DOUIMG_P_FLAG = false;// 是否显示双重映像

	public static int DOUIMG_P_DAY = 20;// 示双重映像显示天数
	/** 图形ID */
	public static final String VOL_P_ID = "volp";// 量线
	public static final String JS_MA_P_ID = "jsmap";// 涨家数均线
	public static final String JS_MA_P0_ID = "jsmap0";// 涨家数均线
	public static final String C_MA_P_ID = "cmap";// 收盘均线
	public static boolean JS_MA_P_FLAG = false;
	public static boolean JS_MA_P0_FLAG = false;
	public static Integer JS_MA_P_TURNOVER = 9;
	public static boolean VOL_P_FLAG = true;
	public static boolean C_MA_P_FLAG = false;// 是否第一条收盘价格均线
	public static int C_MA_P_DAY = 60;// 是否第一条收盘价格均线默认值

}
